package cn.iocoder.yudao.module.famous.doctor.service.treatmentuser;

import cn.hutool.core.util.IdcardUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.yudao.module.famous.doctor.controller.admin.treatmentuser.vo.*;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.treatmentuser.TreatmentUserDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.famous.doctor.convert.treatmentuser.TreatmentUserConvert;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.treatmentuser.TreatmentUserMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.famous.doctor.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 就诊人 Service 实现类
 *
 * @author 档案
 */
@Service
@Validated
public class TreatmentUserServiceImpl implements TreatmentUserService {

    @Resource
    private TreatmentUserMapper treatmentUserMapper;
    @Resource
    private MemberUserService userService;
    @Resource
    private MemberUserMapper memberUserMapper;
    @Override
    public Long createTreatmentUser(TreatmentUserCreateReqVO createReqVO) {

        // 插入
        if (StringUtil.isNotBlank(createReqVO.getIdentityCard())) {
            createReqVO.setIdentityCard(createReqVO.getIdentityCard().toUpperCase());
            verifyIdentityCard(createReqVO.getIdentityCard());
        }
        QueryWrapper<TreatmentUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TreatmentUserDO::getCreator, getLoginUserId());
        queryWrapper.lambda().eq(TreatmentUserDO::getIdentityCard, createReqVO.getIdentityCard());
        if (treatmentUserMapper.selectCount(queryWrapper) > 0) {
            throw exception(TREATMENT_USER_NOT_EXISTS_MAX);
        }
        TreatmentUserDO treatmentUser = TreatmentUserConvert.INSTANCE.convert(createReqVO);

        treatmentUserMapper.insert(treatmentUser);
        //第一次设置默认就诊人
        MemberUserDO user = userService.getUser(getLoginUserId());
        if (user==null) {
            throw exception(USER_ID_NOT_EXISTS);
        }
        if(user.getClinicId()==null) {
            user.setClinicId(treatmentUser.getId());
            memberUserMapper.updateById(user);
        }
        // 返回
        return treatmentUser.getId();
    }

    @Override
    public void updateTreatmentUser(TreatmentUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateTreatmentUserExists(updateReqVO.getId());
        // 更新
        TreatmentUserDO updateObj = TreatmentUserConvert.INSTANCE.convert(updateReqVO);
        treatmentUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteTreatmentUser(Long id) {
        // 校验存在
        validateTreatmentUserExists(id);
        //第一次设置默认就诊人
        // 删除
        treatmentUserMapper.deleteById(id);

        MemberUserDO user = userService.getUser(getLoginUserId());
        Long treatmentUserCount = treatmentUserMapper.selectCount(new LambdaQueryWrapperX<TreatmentUserDO>()
                .eq(TreatmentUserDO::getCreator, getLoginUserId()));
        if(treatmentUserCount==0 && user.getClinicId()!=null) {
            //默认就诊人修改为空
            memberUserMapper.updateByIdClinicId(user);
        }

    }

    private void validateTreatmentUserExists(Long id) {
        if (treatmentUserMapper.selectById(id) == null) {
            throw exception(TREATMENT_USER_NOT_EXISTS);
        }
    }

    @Override
    public TreatmentUserDO getTreatmentUser(Long id) {
        return treatmentUserMapper.selectById(id);
    }

    @Override
    public List<TreatmentUserDO> getTreatmentUserList() {
        return treatmentUserMapper.selectList(new LambdaQueryWrapper<TreatmentUserDO>()
                .eq(TreatmentUserDO::getCreator, getLoginUserId()));
    }

    @Override
    public PageResult<TreatmentUserDO> getTreatmentUserPage(TreatmentUserPageReqVO pageReqVO) {
        return treatmentUserMapper.selectPage(pageReqVO);
    }

    @Override
    public List<TreatmentUserDO> getTreatmentUserList(TreatmentUserExportReqVO exportReqVO) {
        return treatmentUserMapper.selectList(exportReqVO);
    }

    @Override
    public IdcardUtil.Idcard verifyIdentityCard(String  card) {
        String idNum=card.toUpperCase();
        boolean validCard = IdcardUtil.isValidCard(idNum);
        if(!validCard) {
            throw exception(TREATMENT_USER_NOT_EXISTS_IDENTITYCARD);
        }
        return IdcardUtil.getIdcardInfo(idNum);
    }

    @Override
    public Long createNotLoginTreatmentUser(TreatmentUserCreateReqVO createReqVO) {
        // 判断身份证
        if (StringUtil.isNotBlank(createReqVO.getIdentityCard())) {
            createReqVO.setIdentityCard(createReqVO.getIdentityCard().toUpperCase());
            verifyIdentityCard(createReqVO.getIdentityCard());
        }

        QueryWrapper<TreatmentUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TreatmentUserDO::getCreator, getLoginUserId());
        queryWrapper.lambda().eq(TreatmentUserDO::getIdentityCard, createReqVO.getIdentityCard());
        TreatmentUserDO treatmentUserDOS = treatmentUserMapper.selectOne(queryWrapper);
        if ( treatmentUserDOS !=null) {
            //身份证存在  修改
            treatmentUserMapper.updateById(treatmentUserDOS);
            return treatmentUserDOS.getId();
        }else {
            TreatmentUserDO treatmentUser = TreatmentUserConvert.INSTANCE.convert(createReqVO);
            treatmentUserMapper.insert(treatmentUser);
            //第一次设置默认就诊人
            MemberUserDO user = userService.getUser(getLoginUserId());
            if(user.getClinicId()==null) {
                user.setClinicId(treatmentUser.getId());
                memberUserMapper.updateById(user);
            }
            // 返回
            return treatmentUser.getId();
        }


    }

    @Override
    public TreatmentUserDO getTreatmentUserByidentityCard(String identityCard) {
        return  treatmentUserMapper.selectOne(new LambdaQueryWrapperX<TreatmentUserDO>()
                .eqIfPresent(TreatmentUserDO::getIdentityCard, identityCard));
    }

    @Override
    public TreatmentUserDO getTreatmentUserVo(TreatmentUserReqVO reqVO) {
        return treatmentUserMapper.selectOne(new LambdaQueryWrapperX<TreatmentUserDO>()
                .eqIfPresent(TreatmentUserDO::getId, reqVO.getId())
                .likeIfPresent(TreatmentUserDO::getName, reqVO.getName())
                .eqIfPresent(TreatmentUserDO::getSex, reqVO.getSex())
                .eqIfPresent(TreatmentUserDO::getAge, reqVO.getAge())
                .eqIfPresent(TreatmentUserDO::getIdentityCard, reqVO.getIdentityCard())
                .betweenIfPresent(TreatmentUserDO::getCreateTime, reqVO.getCreateTime())
                .eqIfPresent(TreatmentUserDO::getLabel, reqVO.getLabel())
                .eq(TreatmentUserDO::getCreator, getLoginUserId()));
    }

    @Override
    public void setClinic(Long id) {
        //校验是否存在
        validateTreatmentUserExists(id);
        MemberUserDO memberUserDO = memberUserMapper.selectOne(new LambdaQueryWrapperX<MemberUserDO>()
                .eqIfPresent(MemberUserDO::getCreator, getLoginUserId()));
        if (memberUserDO!=null ){
            memberUserDO.setClinicId(id);
            memberUserMapper.updateById(memberUserDO);
        }

    }

}
